package com.li.mybatisconfig.config;

import com.li.mybatisconfig.bean.Function;
import com.li.mybatisconfig.bean.MapperBean;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @Description：手动配置数据源，扫描Mapper
 * @Author：LiDong
 * @Create：2020/9/1
 * @Version：1.0.0
 */
public class MyConfiguration {

    private ClassLoader classLoader=ClassLoader.getSystemClassLoader();

    private Logger logger= LoggerFactory.getLogger(MyConfiguration.class);

    /**
     * 读取数据库的Xml信息
     */
    public Connection getDataSourceInfo(){
        try{

            InputStream inputStream=classLoader.getResourceAsStream("mysqlconfig.xml");
            SAXReader reader=new SAXReader();
            Document document=reader.read(inputStream);
            Element element=document.getRootElement();
            logger.info("==========数据库配置信息读取成功！");
            return getConnection(element);
        }catch (Exception e){
            logger.error(e.getMessage());
            return null;
        }
    }

    /**
     * 得到XMl中的数据库的配置信息返回连接
     */
    private Connection getConnection(Element element) {
            String driverClassName=null;
            String url=null;
            String username=null;
            String password=null;

            if(!"database".equals(element.getName())){
                throw new RuntimeException("数据库xml配置读取错误!");
            }

            List<Object> property = element.elements("property");
            for (Object o : property) {
                Element el= (Element) o;
                String name = el.attribute(0).getValue();
                String value= (String) el.getData();

                if(name==null || value==null){
                    throw new RuntimeException("property信息读取失败！");
                }

                switch (name){
                    case "driverClassName":
                        driverClassName=value;
                        break;
                    case "url":
                        url=value;
                        break;
                    case "username":
                        username=value;
                        break;
                    case "password":
                        password=value;
                        break;
                    default:
                        throw new RuntimeException("==========数据库信息有错误！");
                }
            }
        try {
            Connection connection=null;
            Class.forName(driverClassName);
            logger.info("==========连接数据库获取驱动成功！");
            connection= DriverManager.getConnection(url,username,password);
            logger.info("==========连接数据库成功！");
            return connection;
        }catch (Exception e){
            logger.error(e.getMessage());
            return null;
        }
    }

    /**
     * 读取Mapper和xml中的配置信息
     */
    public MapperBean readMapper(String path){
        MapperBean mapperBean=new MapperBean();
        try{
            InputStream inputStream=classLoader.getResourceAsStream(path);
            SAXReader saxReader=new SAXReader();
            Document document=saxReader.read(inputStream);
            Element root=document.getRootElement();

            // 存储xml文件中namespace的值
            mapperBean.setInterfaceName(root.attributeValue("namespace").trim());
            // 存储方法
            List<Function> list=new ArrayList<>();
            for(Iterator iterator=root.elementIterator();iterator.hasNext();){
                Function function=new Function();
                Element element= (Element) iterator.next();

                String sqlType=element.getName().trim();
                String functionNam=element.attributeValue("id").trim();
                String sql=element.getText().trim();
                String resultType=null;
                Object newinstance=null;
                if(null!=element.attributeValue("resultType")){
                    resultType=element.attributeValue("resultType");
                    try{
                        newinstance=Class.forName(resultType).newInstance();
                    }catch (Exception e){
                        logger.error(e.getMessage());
                    }
                    function.setResultType(resultType);
                }
                function.setFunctionName(functionNam);
                function.setSqlType(sqlType);
                function.setSql(sql);
                list.add(function);
            }
            // 所有的mapper.xml文件解析后保存
            mapperBean.setList(list);
        }catch (Exception e){
            return null;
        }
        return mapperBean;
    }


}
